# -*- coding: utf-8 -*-
"""
Created on Thu May 24 11:12:30 2018

@author: Luther
"""

import os
import chardet


def readtext(path):
    try:
        with open(path) as f:
            text = f.read()
            text = "".join(text.split())
    except UnicodeDecodeError:
        with open(path, encoding="utf-8") as f:
            text = f.read()
            text = "".join(text.split())
    return text


def readunknowntext(path):
    with open(path, 'rb') as f:
        data = f.read()
        ret = chardet.detect(data)
        with open(path, encoding=ret['encoding'], errors='ignore') as f2:
            text = f2.read()
            text = "".join(text.split())
    return text


path = input("请输入结果导出文件夹：")
path_future = input("请输入待检索展望文件目录：")
path_overview = input("请输入待检索回顾文件目录：")
file_list1 = set(
    [x for x in os.listdir(path_future) if os.path.splitext(x)[-1] == '.txt'])
file_list2 = set([
    x for x in os.listdir(path_overview) if os.path.splitext(x)[-1] == '.txt'
])
file_list = file_list1 & file_list2

print("{:}个待检索文件读取成功!".format(len(file_list)))

count = 0
for each in file_list:
    future_file_path = os.path.join(path_future, each)
    overview_file_path = os.path.join(path_overview, each)

    try:
        text1 = readtext(future_file_path)
    except UnicodeDecodeError:
        try:
            text = readunknowntext(future_file_path)
        except UnicodeDecodeError:
            print(future_file_path)

    try:
        text2 = readtext(overview_file_path)
    except UnicodeDecodeError:
        try:
            text = readunknowntext(overview_file_path)
        except UnicodeDecodeError:
            print(overview_file_path)

    text = text2 + "\n" + text1

    result_path = os.path.join(path, each)
    with open(result_path, "w", encoding='utf-8') as f:
        f.write(text)
    count = count + 1
    print("\r当前进度: {:.2f}%".format(count * 100 / len(file_list)), end="")
